﻿#include "../../inc/helper.hpp"

const static int g_request_timeout = 3000;
const static int g_request_retries = 3;
const static char* g_server_endpoint = "tcp://localhost:5555";

zmq::socket_t new_client(zmq::context_t& ctx)
{
	zmq::socket_t client(ctx, zmq::socket_type::req);
	client.connect(g_server_endpoint);

	int linger = 0;
	client.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
	return client;
}

int main()
{
	zmq::context_t ctx;
	zmq::socket_t client = new_client(ctx);

	int sequence = 0;
	int retries_left = g_request_retries;
	while (retries_left)
	{
		std::string request = fmt::format("{}", ++sequence);
		send_string(client, request);

		while (true)
		{
			std::vector<zmq::pollitem_t> items = {
				{client, 0, ZMQ_POLLIN, 0}
			};
			zmq::poll(items, g_request_timeout);
			if (items[0].revents & ZMQ_POLLIN)
			{
				auto replies = zmsg_recv(client);
				std::string msg = to_string(replies.back());
				if (std::atoi(msg.c_str()) == sequence)
				{
					info("server replied OK ({})", msg);
					retries_left = g_request_retries;
					break;
				}
				else
				{
					info("malformed reply from server: {}", msg);
				}
			}
			else if (--retries_left == 0)
			{
				info("server seems to be offline, abandoning");
				break;
			}
			else
			{
				info("no response from server, retrying...");
				client = new_client(ctx);
				send_string(client, request);
			}
		}
	}
}